// *基于数组实现
/* function Stack() {
  // 栈中的属性
  this.items = [];

  // 栈的相关操作
  // 1.入栈
  Stack.prototype.push = function (element) {
    this.items.push(element);
  };
  // 2.从栈中取出元素(删除栈顶元素)
  Stack.prototype.pop = function () {
    return this.items.pop();
  };
  // 3.查看栈顶元素
  Stack.prototype.peek = function () {
    return this.items[this.items.length - 1];
  };
  // 4.判断栈是否为空
  Stack.prototype.isEmpty = function () {
    return this.items.length === 0;
  };
  // 5.获取栈中元素的个数
  Stack.prototype.size = function () {
    return this.items.length;
  };
  // 6.toString()方法
  Stack.prototype.toString = function () {
    let resultString = '';
    for (let i = 0; i < this.items.length; i++) {
      resultString += this.items[i] + ' ';
    }
    return resultString;
  };
} */

class Stack {
  constructor() {
    this.items = [];
  }

  // 1.入栈
  push(element) {
    this.items.push(element);
  }

  // 2.从栈中取出元素(删除栈顶元素)
  pop() {
    return this.items.pop();
  }

  // 3.查看栈顶元素
  peek() {
    return this.items[this.items.length - 1];
  }

  // 4.判断栈是否为空
  isEmpty() {
    return this.items.length === 0;
  }

  // 5.获取栈中元素的个数
  size() {
    return this.items.length;
  }

  // 6.toString()方法
  toString() {
    let resultString = '';
    for (let item of this.items) {
      resultString += item + ' ';
    }
    return resultString.trim();
  }
}

let stack = new Stack();

stack.push(10);
stack.push(20);
stack.push(30);
console.log('实例化后的数组', stack);
console.log('删除栈顶元素', stack.pop());
console.log('查看栈顶元素', stack.peek());
console.log('判断栈是否为空', stack.isEmpty());
console.log('获取栈中元素个数', stack.size());
console.log('toString()方法', stack.toString());
